package com.yc.cloud.admin.service.impl;

import com.yc.cloud.common.orm.CommonPage;
import com.yc.cloud.common.basic.dto.BasePageReqDTO;
import com.yc.cloud.admin.dto.request.HwCameraSnapshotRecordCreateReqDTO;
import com.yc.cloud.admin.dto.request.HwCameraSnapshotRecordUpdateReqDTO;
import com.yc.cloud.admin.dto.request.HwCameraSnapshotRecordPageReqDto;
import com.yc.cloud.admin.vo.HwCameraSnapshotRecordVo;
import com.yc.cloud.entity.HwCameraSnapshotRecord;
import com.yc.cloud.entity.HwCamera;
import com.yc.cloud.entity.HwMonitoringPoint;
import com.yc.cloud.mapper.HwCameraSnapshotRecordMapper;
import com.yc.cloud.mapper.HwCameraMapper;
import com.yc.cloud.mapper.HwMonitoringPointMapper;
import com.yc.cloud.admin.service.HwCameraSnapshotRecordService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.cloud.common.basic.exception.Asserts;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import java.util.Objects;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 摄像头抓图记录表 服务实现类
 * </p>
 *
 * @author kinggu
 * @since 2025-10-10
 */
@Slf4j
@Service
public class HwCameraSnapshotRecordServiceImpl extends ServiceImpl<HwCameraSnapshotRecordMapper, HwCameraSnapshotRecord> implements HwCameraSnapshotRecordService {

    @Resource
    private HwCameraMapper hwCameraMapper;

    @Resource
    private HwMonitoringPointMapper hwMonitoringPointMapper;

    @Resource
    private com.yc.cloud.common.oss.service.OssFileService ossFileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HwCameraSnapshotRecordVo create(HwCameraSnapshotRecordCreateReqDTO createReqDTO) {
        HwCameraSnapshotRecord entity = new HwCameraSnapshotRecord();
        BeanUtils.copyProperties(createReqDTO, entity);
        boolean success = save(entity);
        if (success) {
            return getVOById(entity.getId());
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HwCameraSnapshotRecordVo update(HwCameraSnapshotRecordUpdateReqDTO updateReqDTO) {
        // 1. 校验待更新的记录是否存在
        if (getById(updateReqDTO.getId()) == null) {
            Asserts.fail("记录不存在，无法更新");
        }
        HwCameraSnapshotRecord entity = new HwCameraSnapshotRecord();
        BeanUtils.copyProperties(updateReqDTO, entity);
        boolean success = updateById(entity);
        if (success) {
            return getVOById(entity.getId());
        }
        return null;
    }

    @Override
    public CommonPage<HwCameraSnapshotRecordVo> list(HwCameraSnapshotRecordPageReqDto pageReqDTO) {
        QueryWrapper<HwCameraSnapshotRecord> queryWrapper = new QueryWrapper<>();

        // 摄像头ID过滤
        if (pageReqDTO.getCameraId() != null) {
            queryWrapper.eq(HwCameraSnapshotRecord.CameraId, pageReqDTO.getCameraId());
        }

        // 日期范围过滤（使用 create_time 字段）
        if (pageReqDTO.getStartDate() != null) {
            // 创建时间 >= 查询日期的开始（00:00:00）
            queryWrapper.ge("create_time", pageReqDTO.getStartDate().atStartOfDay());
        }
        if (pageReqDTO.getEndDate() != null) {
            // 创建时间 <= 查询日期的结束（23:59:59）
            queryWrapper.le("create_time", pageReqDTO.getEndDate().atTime(23, 59, 59));
        }

        // 排序
        if (StrUtil.isNotEmpty(pageReqDTO.getSortBy())) {
            if (Objects.equals(BasePageReqDTO.ORDER_DESC, pageReqDTO.getOrder())) {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(pageReqDTO.getSortBy()));
            } else {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(pageReqDTO.getSortBy()));
            }
        } else {
            // 默认按创建时间倒序
            queryWrapper.orderByDesc("create_time");
        }

        // 关键字模糊查询
        if (StrUtil.isNotEmpty(pageReqDTO.getKeyword())) {
            // TODO: 请根据业务需求，修改需要模糊查询的字段
        }
        
        // 根据 page 参数决定是否分页
        if (Boolean.TRUE.equals(pageReqDTO.getPage())) {
            Page<HwCameraSnapshotRecord> page = new Page<>(pageReqDTO.getPageNum(), pageReqDTO.getPageSize());
            Page<HwCameraSnapshotRecord> dbPage = baseMapper.selectPage(page, queryWrapper);
            IPage<HwCameraSnapshotRecordVo> voPage = dbPage.convert(this::convertToVo);
            return CommonPage.restPage(voPage);
        } else {
            List<HwCameraSnapshotRecord> allRecords = baseMapper.selectList(queryWrapper);
            CommonPage<HwCameraSnapshotRecordVo> result = new CommonPage<>();
            result.setList(convertToVoList(allRecords));
            result.setTotal((long) allRecords.size());
            result.setPageNum(1);
            result.setPageSize(allRecords.size());
            result.setTotalPage(1);
            return result;
        }
    }

    @Override
    @Deprecated
    public CommonPage<HwCameraSnapshotRecordVo> list(BasePageReqDTO pageReqDTO) {
        // 向后兼容：转换为新的DTO
        HwCameraSnapshotRecordPageReqDto newPageReqDTO = new HwCameraSnapshotRecordPageReqDto();
        BeanUtils.copyProperties(pageReqDTO, newPageReqDTO);
        return list(newPageReqDTO);
    }

    @Override
    public HwCameraSnapshotRecordVo getVOById(Long id) {
        HwCameraSnapshotRecord entity = getById(id);
        return convertToVo(entity);
    }

    @Override
    public List<HwCameraSnapshotRecordVo> convertToVoList(List<HwCameraSnapshotRecord> entityList) {
        if (entityList == null) {
            return null;
        }
        return entityList.stream()
                .map(this::convertToVo)
                .collect(Collectors.toList());
    }

    private HwCameraSnapshotRecordVo convertToVo(HwCameraSnapshotRecord entity) {
        if (entity == null) {
            return null;
        }
        HwCameraSnapshotRecordVo vo = new HwCameraSnapshotRecordVo();
        BeanUtils.copyProperties(entity, vo);

        // 通过 OSS fileId 获取访问URL
        if (StrUtil.isNotEmpty(entity.getFileId())) {
            vo.setImageUrl(ossFileService.getOssFileUrl(entity.getFileId()));
        }
        if (StrUtil.isNotEmpty(entity.getThumbnailFileId())) {
            vo.setThumbnailUrl(ossFileService.getOssFileUrl(entity.getThumbnailFileId()));
        }

        // 查询并设置相机名称
        if (entity.getCameraId() != null) {
            HwCamera camera = hwCameraMapper.selectById(entity.getCameraId());
            if (camera != null) {
                vo.setCameraName(camera.getName());

                // 如果相机关联了监控点，查询并设置监控点名称
                if (camera.getMonitoringPointId() != null) {
                    HwMonitoringPoint monitoringPoint = hwMonitoringPointMapper.selectById(camera.getMonitoringPointId());
                    if (monitoringPoint != null) {
                        vo.setMonitoringPointName(monitoringPoint.getName());
                    }
                }
            }
        }

        return vo;
    }

    @Override
    public HwCameraSnapshotRecord get(Long id) {
        return getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        // 1. 校验待删除的记录是否存在
        HwCameraSnapshotRecord record = getById(id);
        if (record == null) {
            Asserts.fail("记录不存在，无法删除");
        }
        
        // 2. 删除关联的OSS文件资源（包括物理文件和数据库记录）
        if (StrUtil.isNotEmpty(record.getFileId())) {
            ossFileService.deleteByFileId(record.getFileId());
        }
        if (StrUtil.isNotEmpty(record.getThumbnailFileId())) {
            ossFileService.deleteByFileId(record.getThumbnailFileId());
        }
        
        // 3. 删除数据库记录
        return removeById(id);
    }
} 